<?php

/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class wms_ctl_admin_deliverycomp extends desktop_controller
{

    var $workground = 'wms_ctl_admin_deliverycomp';
    var $pagelimit = 10;
    var $stocknotice_model;

    public function __construct($app)
    {
        parent::__construct($app);
        $this->member_model = $this->app->model('deliverycomp');
        header("cache-control: no-store, no-cache, must-revalidate");
    }

    //备货通知单首页
    function index()
    {

        $filter = '';
         //add by liyb 根据操作员带出所属组织进行过滤
         $org = kernel::single('desktop_user')->get_srcorg();
         $is_super = kernel::single('desktop_user')->is_super();
            if (!$is_super){
                    $filter['srcorg'] = $org;
                }
        //获取操作员管辖仓库  
            /*$oBranch = app::get('ome')->model('branch');
            $is_super = kernel::single('desktop_user')->is_super();
            if (!$is_super){
                $branch_ids = $oBranch->getBranchByUser(true);
                if ($branch_ids){
                    $filter['branch_id'] = $branch_ids;
                }else{
                    $filter['branch_id'] = 'false';
                }
            }*/

        $params = array(
            'title' => '发货完成',
            'actions' => array(
                'new' => array(
                    'label' => '新建',
                    'href' => 'index.php?app=wms&ctl=admin_deliverycomp&act=add_deliverycomp',
                    'target' => '_blank',
                ),
                'confirm' => array(
                    'label' => '确认',
                    'submit' => 'index.php?app=wms&ctl=admin_deliverycomp&act=doConfirm',
                ),
                'delete' => array(
                    'label' => '删除',
                    'submit' => 'index.php?app=wms&ctl=admin_deliverycomp&act=doDelete',
                ),
            ),
            'base_filter' => $filter,
            //'base_filter' => '',
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag' => false,
            'use_buildin_recycle' => false,
            'use_buildin_export' => true,
            'use_buildin_import' => false,
            'use_buildin_filter' => true,
            'allow_detail_popup' => true,
            'max_actions' => 8,
            'use_view_tab' => false,
            'orderBy' => 'create_time desc',
        );
        //var_dump($params);
        $this->finder('wms_mdl_deliverycomp', $params);


    }
    //添加备货
    function add_deliverycomp()
    {


        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $time_begin = mktime(0, 0, 0, $m, $d, $y);
        $time_end = mktime(23, 59, 59, $m, $d, $y);
        $delivery_model = $this->app->model('deliverycomp');
        $filter['create_time|between'] = array($time_begin, $time_end);
        $delivery = $delivery_model->getList('deliverycomp_bn', $filter, 0, 1, 'create_time desc');

        if ($delivery[0]['deliverycomp_bn'] == '') {
            $this->pagedata['cur_date'] = 'DC' . date('Ymd', time()) . '01';
        } else {
            $bn = substr($delivery[0]['deliverycomp_bn'], 10, 2);
            $num = intval($bn) + 1;
            if ($num <= 9) {
                $this->pagedata['cur_date'] = 'DC' . date('Ymd', time()) . '0' . $num;
            } else {
                $this->pagedata['cur_date'] = 'DC' . date('Ymd', time()) . $num;
            }
        }
        $operator = kernel::single('desktop_user')->get_name();
        $this->pagedata['comp_date'] = date('Y-m-d', time());
        $this->pagedata['time'] = time();
        $this->pagedata['operator'] = $operator;
        //add by liyb 根据操作员带出所属组织
        $org = kernel::single('desktop_user')->get_srcorg();
        $this->pagedata['srcorg'] = $org;

        //add by ivan 根据操作员带出所属区域
        $area = kernel::single('desktop_user')->get_area();
        $this->pagedata['area'] = $area;

        $this->singlepage('admin/deliverycomp/deliverycomp_add.html');
    }

    /**
     * 基础物料列表弹窗数据获取方法
     *
     * @param Void
     * @return String
     */
    function finddelivery($supplier_id = null)
    {

        // $base_filter['print_status'] = '0';
        // $base_filter['status'] = '0';
        // $base_filter['is_ship'] = 'false';
        // //$base_filter['deliverytype'] = 'deliver';
        $delivery_start = strtotime($_GET['comp_date']);
        $delivery_end = strtotime($_GET['comp_date']) + 86399;
        /*//获取操作员管辖仓库  
            $oBranch = app::get('ome')->model('branch');
            $is_super = kernel::single('desktop_user')->is_super();
            if (!$is_super){
                $branch_ids = $oBranch->getBranchByUser(true);
                if ($branch_ids){
                    $base_filter['branch_id'] = $branch_ids;
                }else{
                    $base_filter['branch_id'] = 'false';
                }
            }*/
            //var_dump($branch_ids);
            //var_dump($base_filter);
        $base_filter['is_comp'] = 'false';
        $base_filter['status'] = 'confirmed';
         //add by liyb 获取操作员所属组织
        $org = kernel::single('desktop_user')->get_srcorg();
        $base_filter['srcorg'] = $org;

        //add by ivan 获取操作员所属区域
        $area = kernel::single('desktop_user')->get_area();
        $base_filter['area'] = $area;

        if ($_GET['sendType'] == 2) {
            $base_filter['deliverynote_time|between'] = array($delivery_start, $delivery_end);
        }
        $base_filter['sendType'] = $_GET['sendType'];

        $params = array(
            'title' => '送货单',
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag' => false,
            'use_buildin_recycle' => false,
            'use_buildin_export' => false,
            'use_buildin_import' => false,
            'use_buildin_filter' => true,
            'base_filter' => $base_filter,
        );
        //var_dump($params);
        $this->finder('wms_mdl_deliverynote', $params);
    }

    function getdeliverys()
    {
        //$basicMaterialSelect    = kernel::single('delivery_select');#基础物料 ExBOY
        //$basicMaterialBarcode    = kernel::single('material_basic_material_barcode');#条形码 ExBOY
        $pro_id = $_POST['product_id'];
        if (is_array($pro_id)) {
            $filter['id'] = $pro_id;
        }
        /*
             * 获取操作员管辖仓库
             */
        /*    $oBranch = app::get('ome')->model('branch');
            $is_super = kernel::single('desktop_user')->is_super();
            if (!$is_super){
                $branch_ids = $oBranch->getBranchByUser(true);
                if ($branch_ids){
                    $filter['branch_id'] = $branch_ids;
                }else{
                    $filter['branch_id'] = 'false';
                }
            }*/
            //var_dump($filter);
        if (isset($_POST['filter']['advance']) && $_POST['filter']['advance']) {
            $arr_filters = explode(',', $_POST['filter']['advance']);
            foreach ($arr_filters as $obj_filter) {
                $arr = explode('=', $obj_filter);
                $filter[$arr[0]] = $arr[1];
            }
            if ($filter['_delivery_time_search'] == 'than' || $filter['_delivery_time_search'] == 'lthan') {
                $filter['_DTYPE_TIME'][0] = $filter['_DTYPE_TIME[]'];
                $filter['_DTIME_']['H']['delivery_time'] = $filter['_DTIME_[H][delivery_time]'];
                $filter['_DTIME_']['M']['delivery_time'] = $filter['_DTIME_[M][delivery_time]'];
            }
            if ($filter['_delivery_time_search'] == 'between') {
                $filter['_DTYPE_TIME'][0] = $filter['_DTYPE_TIME[]'];
                $filter['_DTIME_']['H']['delivery_time_from'] = $filter['_DTIME_[H][delivery_time_from]'];
                $filter['_DTIME_']['M']['delivery_time_from'] = $filter['_DTIME_[M][delivery_time_from]'];
                $filter['_DTIME_']['H']['delivery_time_to'] = $filter['_DTIME_[H][delivery_time_to]'];
                $filter['_DTIME_']['M']['delivery_time_to'] = $filter['_DTIME_[M][delivery_time_to]'];
            }
        }

        $delivery_model = $this->app->model('deliverynote');
        $delivery = $delivery_model->getList('deliverynote_bn,id', $filter);

        if (!empty($delivery)) {
            foreach ($delivery as $k => $item) {
                $item['product_id'] = $item['id'];
                $item['delivery_bn'] = $item['deliverynote_bn'];
                $rows[] = $item;
            }
        }
        echo "window.autocompleter_json=" . json_encode($rows);
    }

    //保存备货通知单
    function doSave()
    {
        $this->begin();
        $deliverynote_model = app::get('wms')->model('deliverynote_line');
        $shopMdl = app::get('ome')->model('shop');
        $deliverycomp_model = $this->app->model('deliverycomp');
        $delivery_ID = $_POST['delivery_ID'];
        if (!$_POST['delivery_ID']) {
            $this->end(false, '未选择送货单不能保存');
        }
        $name = $_POST['purchase_name'];
        $memo = $_POST['memo'];
        $operator = $_POST['operator'];
        $comp_date = $_POST['comp_date'];
         //add by liyb
        $srcorg = $_POST['srcorg'];

         //add by ivan
        $area = $_POST['area'];
        foreach ($delivery_ID as $k => $v) {

            $shopId = $deliverynote_model->getList('shop_id', array('deliverynote_id' => $v));
            foreach ($shopId as $r => $row) {
                $sendType = $shopMdl->getList('sendType', array('shop_id' => $row['shop_id']));
                if ($sendType[0]['sendType'] == 1) {
                    $sendTypeNum1 = 1;
                } else {
                    $sendTypeNum2 = 2;
                }
            }
        }
        if ($sendTypeNum1 && $sendTypeNum2) {
            $this->end(false, '同时存在按天发货和整车发货店铺的送货单');
        } elseif ($sendTypeNum1 && !$sendTypeNum2) {

            $y = date("Y", $comp_date);
            $m = date("m", $comp_date);
            $d = date("d", $comp_date);
            $time_begin = strtotime($comp_date);
            $time_end = strtotime($comp_date) + 2;
            $filter['deliverycomp_time|between'] = array($time_begin, $time_end);

            $delivery = $deliverycomp_model->getList('deliverycomp_bn', $filter, 0, 1, 'create_time desc');

            if ($delivery[0]['deliverycomp_bn'] == '') {
                $cur_date = 'DC' . date('ymd', strtotime($comp_date)) . '01';
            } else {
                $bn = substr($delivery[0]['deliverycomp_bn'], 8, 2);
                $num = intval($bn) + 1;
                if ($num <= 9) {
                    $cur_date = 'DC' . date('ymd', strtotime($comp_date)) . '0' . $num;
                } else {
                    $cur_date = 'DC' . date('ymd', strtotime($comp_date)) . $num;
                }
            }
        } else {
            $time_begin = strtotime($comp_date);
            $time_end = strtotime($comp_date) + 2;
            $filter['deliverycomp_time|between'] = array($time_begin, $time_end);

            $delivery = $deliverycomp_model->getList('deliverycomp_bn,sendType', $filter, 0, 1, 'create_time desc');
            
            if ($delivery[0]['deliverycomp_bn'] && $delivery[0]['sendType'] == 2) {
                $this->end(false, '已经生成一张发货完成单');
            }

            if ($delivery[0]['deliverycomp_bn'] == '') {
                $cur_date = 'DC' . date('ymd', strtotime($comp_date)) . '01';
            } else {
                $bn = substr($delivery[0]['deliverycomp_bn'], 8, 2);
                $num = intval($bn) + 1;
                if ($num <= 9) {
                    $cur_date = 'DC' . date('ymd', strtotime($comp_date)) . '0' . $num;
                } else {
                    $cur_date = 'DC' . date('ymd', strtotime($comp_date)) . $num;
                }
            }
        }
        $arr_order = '';
        $arr_order['deliverycomp']['deliverycomp_bn'] = $cur_date;
        $arr_order['deliverycomp']['remark'] = $_POST['memo'];
        $arr_order['deliverycomp']['operator'] = $_POST['operator'];
        $arr_order['deliverycomp']['create_time'] = time();
        $arr_order['deliverycomp']['sendType'] = $_POST['sendType'];
        $arr_order['deliverycomp']['deliverycomp_time'] = strtotime($comp_date) + 1;
        //add by liyb
        $arr_order['deliverycomp']['srcorg'] = $_POST['srcorg'];
        //add by ivan
        $arr_order['deliverycomp']['area'] = $_POST['area'];

        //创建OMS备货通知单
        $res = $deliverycomp_model->insert($arr_order['deliverycomp']);

        $orders_obj = $this->app->model('deliverynote');
        $deliverycomp_delis_model = $this->app->model('deliverycomp_line');
        foreach ($delivery_ID as $key => $value) {
            $orders = $orders_obj->getList('deliverynote_bn', array('id' => $value), 0, 1);

            $arr_line = '';
            $arr_line['deliverycomp']['deliverynote_bn'] = $orders[0]['deliverynote_bn'];
            $arr_line['deliverycomp']['deliverynote_id'] = $value;
            $arr_line['deliverycomp']['deliverycomp_id'] = $res;
            $deliverycomp_delis_model->insert($arr_line['deliverycomp']);

            $orders_obj->db->exec("update sdb_wms_deliverynote set is_comp = 'true' where  id in(" . $value . ")");
        }

        $this->end(true, '已完成');
    }

    function getdividefeenew($order_id,$bn)
    {
      $sql="SELECT  items.bn,sum(items.divide_order_fee) divide_order_fee,sum(items.nums) nums from sdb_ome_orders os 
              inner join sdb_ome_order_items items on os.order_id=items.order_id
              where os.order_id='$order_id' and items.bn='$bn' and items.delete='false' 
              group by items.bn ";
      $rows = kernel::database()->select($sql);
      return $rows;
    }

    function doPushQueue()
    {
        
         $bldata = array(
            'op_id' => 16777210, 
            'op_name' => 'system',
            'createtime' => time(),
            'batch_number' => 1,
            'log_type' => 'syncoms',
            'log_text'=>serialize(array(
            'dlycompid' => 'testdlycomp',
            )),
        );
        $blObj = app::get('wms')->model('batch_log');
        $result = $blObj->save($bldata);
        //同步发货完成任务加队列
        $push_params = array(
            'data' => array(
                'log_text' => $bldata['log_text'],
                'log_id' => $bldata['log_id'],
                'task_type' => 'autodlycomp'
            ),
            'url' => kernel::openapi_url('openapi.autotask', 'service')
        );
        kernel::single('taskmgr_interface_connecter')->push($push_params);
    }

    //确认动作
    // function doConfirm()
    // {
    //     $this->begin('index.php?app=wms&ctl=admin_deliverycomp&act=index');

    //     $this->_request = kernel::single('base_component_request');
    //     $postData = $this->_request->get_post();
    //     if ($postData['isSelectedAll'] == '_ALL_') {
    //         $this->end(false, '不可全选！');
    //     }
    //     if (count($postData['id']) > 1) 
    //     {
    //         $this->end(false, '请单条确认！');
    //     }
    //     $deliverycomp_model = $this->app->model('deliverycomp');
    //     $orderTotal = $deliverycomp_model->count(array('id' => $postData['id'][0], 'status|noequal' => 'unconfirmed'));
    //     if ($orderTotal > 0) 
    //     {
    //         $this->end(false, '不可选择已发送的！');
    //     }
    //     $sync=kernel::single('wms_autotask_task_syncoms');
    //     $sync->dosync($postData['id'][0]);

    //     $this->end(true, '提交到过数队列！');
    // }
    //确认动作
    function doConfirm()
    {
        $this->begin('index.php?app=wms&ctl=admin_deliverycomp&act=index');

        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit', '512M');
        set_time_limit(1000);
        $this->_request = kernel::single('base_component_request');
        $postData = $this->_request->get_post();
        //发货完成表
        $deliverycomp_model = $this->app->model('deliverycomp');
        $deliverycomp_delis_model = $this->app->model('deliverycomp_line');
        $deliveryMdl = $this->app->model('delivery');
        $deliveryItemsMdl = $this->app->model('delivery_items');
        $shop_obj = app::get('ome')->model('shop');
        $sales_material = app::get('material')->model('basic_material');
        $sales_material_ext = app::get('material')->model('basic_material_ext');
        $orderItemsMdl = app::get('ome')->model('order_items');
        $orderMdl = app::get('ome')->model('orders');
        $xml_arr = array();
        $carno = '';
        if ($postData['isSelectedAll'] == '_ALL_') {
            $this->end(false, '不可全选！');
        }
        if (count($postData['id']) > 1) {
            $this->end(false, '请单条确认！');
        }
        $orderTotal = $deliverycomp_model->count(array('id' => $postData['id'][0], 'status|noequal' => 'unconfirmed'));
        if ($orderTotal > 0) {
            $this->end(false, '不可选择已发送的！');
        }
        $deliveryCompData=$deliverycomp_model->dump(array('id' => $postData['id'][0]),'srcorg');
        

        $delivery_bn = '';
        $comp_data = $deliverycomp_model->getDeliveryInfo($postData['id'][0]);


        if ($comp_data) {

            $orderIdArr=array();
            foreach ($comp_data as $val) {
                $orderIdArr[]=$val['order_id'];
            }
            //判断实付对不对
            // if(count($orderIdArr)>0){
            //     $orderIdArr=array_unique($orderIdArr);
            //     $errorOrderBnArr=$orderMdl->check_divide_orders($orderIdArr);
            //     if(count($errorOrderBnArr)>0){
            //         $order_bns=join(',',$errorOrderBnArr);
            //         print($order_bns.'/价格存在异常！');
            //         return false;
            //     }
            // }
            foreach ($comp_data as $cv) {
                //已经确定的订单  无需在操作
                if($cv['dnl_status']=='confirmed'){
                    continue;
                }
                $shopData = $shop_obj->getRow($cv['shop_id']);
                $shop_bn = $shopData['AXCustomer'];
                if ($shop_bn == '') 
                {
                    continue;
                }
                $deliveryItemsData = $deliveryItemsMdl->getList('*', array('delivery_id' => $cv['delivery_id']));
                // $orderIdArr = $deliveryMdl->getOrderIdByDeliveryId($cv['delivery_id']);
                if (!empty($deliveryItemsData)) 
                {
                    foreach ($deliveryItemsData as $v) 
                    {
                        $salesMData = $sales_material->dump(array('material_bn' => $v['bn']), 'bm_id');
                        $unit = $sales_material_ext->dump(array('bm_id' => $salesMData['bm_id']), 'unit');

                        // add by ldward 2018-0830 因订单同时存在普通及促销，导致取价不等；
                        //   $orderItemFilter['order_id']=$cv['order_id'];
                        // $orderItemFilter['bn']=$v['bn'];
                        // $orderItemFilter['delete']='false';
                        // $orderItemFilter['item_type|in']=array('product','pkg');
                        // $orderItemData = $orderItemsMdl->dump($orderItemFilter,'divide_order_fee,part_mjz_discount,nums');

                        // if($orderItemData['quantity']==''  || empty($orderItemData['quantity'])){
                        //     $num=0;
                        // }else{
                        //     $num = $orderItemData['quantity'];
                        // }
                        // if($orderItemData['divide_order_fee']==''  || empty($orderItemData['divide_order_fee'])){
                        //     $itemFee=0;
                        // }else{
                        //     $itemFee = $orderItemData['divide_order_fee'];
                        // }
                        // $SalesPrice = round($itemFee/$num,3);

                        $divide_order_fee=$this->getdividefeenew($cv['order_id'],$v['bn']);
                        //add by ldward 20181121 如果为经销商类型，则必须校验价格异常
                        if($shopData['leemantype']!='3')
                        {
                            if($divide_order_fee[0]['divide_order_fee']<=0)
                            {
                                //print($cv['delivery_bn'].'发货单价格存在异常！');
                                //return false;
                            }
                        }
                        $SalesPrice = round(($divide_order_fee[0]['divide_order_fee']/$divide_order_fee[0]['nums']),4);
                        
                        $branch_bn = $cv['branch_bn'];
                        if($cv['branch_bn'] == 'ZYC001'){
                            $branch_bn = 'W023';
                        }
                    

                        $tmp = $shop_bn .'-'.$shopData['shop_bn'].'-' . $v['bn'] . '-' . $SalesPrice . '-' . $branch_bn. '-' . $unit['unit'] . '-' . $cv['axshipno'] . '-' . $cv['axorderno'] . '-' . $cv['carno'];
                        $salesPlatfrom = '其他';
                        if ($shopData['shop_type'] != '') {
                            $salesPlatfrom = ome_shop_type::shop_name($shopData['shop_type']);
                        }
                        if (isset($number_tmp[$tmp])) {
                            $number_tmp[$tmp] += $v['number'];
                        } else {
                            $number_tmp[$tmp] = $v['number'];
                        }
                        $xml[$tmp] = '<Cust>'
                            . '<CustAccount>' . $shop_bn . '</CustAccount>'
                            . '<ItemId>' . $v['bn'] . '</ItemId>'
                            . '<SalesPrice>' . $SalesPrice . '</SalesPrice>'
                            . '<SalesQty>' . $number_tmp[$tmp]. '</SalesQty>'
                            . '<Branch>' . $branch_bn. '</Branch>'
                            . '<SalesUnit>' . $unit['unit'] . '</SalesUnit>'
                            . '<PackingSlipId>' . $cv['axshipno'] . '</PackingSlipId>'
                            . '<SalesId>' . $cv['axorderno'] . '</SalesId>'
                            . '<LicencePlateNo>' . $cv['carno'] . '</LicencePlateNo>'
                            . '<shopName>' . $shopData['shop_bn'] . '</shopName>'
                            . '<salesPlatfrom>' . $salesPlatfrom . '</salesPlatfrom>'
                            . '</Cust>';
                    }
                }
            }
        }

        if (empty($xml)) {
            $this->end(false, 'oms无同步信息');
        }

        error_log(date('Y-m-d H:i:s') . '确认/'.var_export($xml,true) , 3, DATA_DIR . '/AXToOMs_' . date('Y-m-d') . '.log');
        
        foreach ($xml as $key => $value) {
            $rel_xml .= $value;
        }
        try {
            $xml = "<CustGroup>" . $rel_xml . "<Attribute><IsCreatePickingRoute>yes</IsCreatePickingRoute></Attribute></CustGroup>";
            date_default_timezone_set("PRC");
            ini_set('soap.wsdl_cache_enabled', "0"); //关闭wsdl缓存
            ini_set('default_socket_timeout', 5000);    // timeout
            $param['str'] = $xml;
            $param['company'] = $deliveryCompData['srcorg'];
            if(WITH_QIMEN){
                 $res=kernel::single('erpapi_rpc_qimen')->call('CreateSalesOrder',$param);
                 $res=json_decode($res,1);
            }else{
                $webservice_url = HOST_AXToOMs;
                $client = new SoapClient($webservice_url);
                $res = $client->__soapCall('CreateSalesOrder', array('parameters' => $param));
                $res['response']['data'] = $res->CreateSalesOrderResult;
                //var_dump($res->CreateSalesOrderResult);
            }
            
            // $res['response']['data']='[{"Code":"0","Msg":"已存在此订单：ESWQ18033001 ","subMsg":"ESWQ18033001","AxOrderNo":"ESWQ18033001"}]';
            error_log(date('Y-m-d H:i:s') . '发送数据/' . var_export($param, true) . '返回数据/' . var_export($res, true), 3, DATA_DIR . '/AXToOMs_' . date('Y-m-d') . '.log');
            if (isset($res['response']['data']) && !empty($res['response']['data'])) 
            {
                $arr = json_decode($res['response']['data'], '1');
                if (count($arr) > 0) 
                {
                    $msg = '';
                    $db=kernel::database();
                    $axorderno='';
                    //$this->begin();
                    foreach ($arr as $key => $value) {
                        
                        if($value['Code'] == '0' || ($value['Code'] == '99' && (strpos($value['Msg'],"该记录已存在") != false) )){
                            $axorderno=$value['AxOrderNo'];
                            $db->exec("update sdb_wms_deliverynote_line set status = 'confirmed',last_modify=".time()." where axorderno = '$axorderno' ");
                        }else{
                            $msg .= "(" . $value['Msg'] . ")";
                        }
                    }
                    if (empty($msg) && isset($msg)) {
                        $db->exec("update sdb_wms_deliverycomp set status = 'confirmed' ,last_modify=".time()." where id in(" . implode(',', $postData['id']) . ")");
                        $this->end(true, '已完成', 'index.php?app=wms&ctl=admin_deliverycomp&act=index');
                    } else {
                        print($msg);
                    }
                } else {
                    print($res['response']['data']);
                }
            } else {
                print('奇门接口异常：'.json_encode($res['response']));
            }
        } catch (Exception $e) {
            print('接口出错：' . $e->getMessage());
        }
    }


    //确认动作
    function doDelete()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit', '512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_deliverycomp&act=index");
        $this->_request = kernel::single('base_component_request');
        $order_info = $this->_request->get_post();

        $deliverycomp_delis_model = $this->app->model('deliverycomp_line');
        $deliverycomp_model = $this->app->model('deliverycomp');
        $orders_obj = $this->app->model('deliverynote');

        if ($order_info['isSelectedAll'] == '_ALL_') {

            $orders = $deliverycomp_model->getList('*', array(), 0, -1);
            foreach ($orders as $key_o => $order) {
                $value = $order['id'];
                if ($order['status'] == 'unconfirmed') {
                    $deliverycomp_delis = $deliverycomp_delis_model->getList('*', array('deliverycomp_id' => $value));
                    foreach ($deliverycomp_delis as $key => $delivery_id) {
                        $orders_obj->db->exec("update sdb_wms_deliverynote set is_comp = 'false' where  id in(" . $delivery_id['deliverynote_id'] . ")");
                    }

                    $deliverycomp_model->db->exec("delete from sdb_wms_deliverycomp_line  where  deliverycomp_id in(" . $value . ");");
                    $deliverycomp_model->db->exec("delete from sdb_wms_deliverycomp  where  id in(" . $value . ");");
                } else {
                    $this->end(false, '完成单号【' . $orders[0]['deliverycomp_bn'] . '】状态已确认，删除失败！');
                }
            }
        } else {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg = "多选不能超过系统表单最大提交数【" . $max_input_vars . "】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value) {
                $orders = $deliverycomp_model->getList('*', array('id' => $value), 0, 1);

                if ($orders[0]['status'] == 'unconfirmed') {
                    $deliverycomp_delis = $deliverycomp_delis_model->getList('*', array('deliverycomp_id' => $value));
                    foreach ($deliverycomp_delis as $key => $delivery_id) {
                        $orders_obj->db->exec("update sdb_wms_deliverynote set is_comp = 'false' where  id in(" . $delivery_id['deliverynote_id'] . ")");
                    }

                    $deliverycomp_model->db->exec("delete from sdb_wms_deliverycomp_line  where  deliverycomp_id in(" . $value . ");");
                    $deliverycomp_model->db->exec("delete from sdb_wms_deliverycomp  where  id in(" . $value . ");");
                } else {
                    $this->end(false, '完成单号【' . $orders[0]['deliverycomp_bn'] . '】状态已确认，删除失败！');
                }
            }
        }
        $this->end(true, '已完成');
    }

    /**
     * 编辑采购单
     *
     */
    function editOrderform()
    {
        $this->begin('index.php?app=wms&ctl=admin_deliverycomp&act=index');

        $id = $_GET['id'];

        $poObj = app::get('purchase')->model('po');
        $suObj = app::get('purchase')->model('supplier');
        $brObj = app::get('ome')->model('branch');

        $data = $poObj->dump($po_id, '*', array('po_items' => array('*')));

        //当前供应商
        $supplier_detail = $suObj->dump($data['supplier_id'], 'supplier_id,name');
        $this->pagedata['supplier_detail'] = $supplier_detail;

        if (!$branch_mode) {
            $branch_mode = 'single';
        }
        $this->pagedata['branch_mode'] = $branch_mode;

        $su = $suObj->dump($data['supplier_id'], 'name');
        $br = $brObj->dump($data['branch_id'], 'name');
        $data['branch_name'] = $br['name'];
        $data['supplier_name'] = $su['name'];
        //到货天数
        $diff_time = $data['arrive_time'] - $data['purchase_time'];
        $data['diff_days'] = floor($diff_time / (24 * 60 * 60));
        $this->pagedata['po_items'] = $data['po_items'];
        $data['memo'] = unserialize($data['memo']);
        $this->pagedata['po'] = $data;
        //$this->singlepage("admin/purchase/purchase_edit.html");
        $this->singlepage("admin/deliverycomp/deliverycomp_edit.html");
    }

}
